package com.tarena.lbs.coupon.controller;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.coupon.api.pojo.param.UserCouponsParam;
import com.tarena.lbs.coupon.pojo.param.CouponParam;
import com.tarena.lbs.coupon.pojo.query.UserCouponCodeQuery;
import com.tarena.lbs.coupon.pojo.query.UserCouponQuery;
import com.tarena.lbs.coupon.pojo.vo.CouponVO;
import com.tarena.lbs.coupon.pojo.vo.UserCouponsVO;
import com.tarena.lbs.coupon.service.CouponService;
import com.tarena.lbs.coupon.util.ExcelExporter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 处理和优惠券数据业务有关的接口
 */
@RestController
@Slf4j
@Tag(name="优惠券模块")
public class CouponController {


    @Autowired
    private CouponService couponService;

    @Operation(summary = "查询当前商家优惠券分页列表")
    @PostMapping("/admin/marketing/coupon/info/list")
    public Result<PageResult<CouponVO>> pageList(@RequestBody CouponParam couponParam) throws BusinessException{
        PageResult<CouponVO> voPage = couponService.pageList(couponParam);
        log.debug("查询当前商家优惠券分页列表");
        return new Result<>(voPage);
    }


    @Operation(summary = "新增优惠券")
    @PostMapping("/admin/marketing/coupon/info/save")
    public Result<Void> addCoupon(@RequestBody CouponParam couponParam)throws BusinessException{
        couponService.save(couponParam);

        return Result.success();
    }

    @Operation(summary = "查询优惠券详情")
    @GetMapping("/admin/marketing/coupon/info/detail/{id}")
    public Result<CouponVO> detail(@PathVariable("id") Integer id)
        throws BusinessException{
        CouponVO couponVO=couponService.detail(id);
        return new Result<>(couponVO);
    }



    @Operation(summary = "领取优惠券")
    @PostMapping("/marketing/user/receive/save")
    public Result<Void> receiveCoupon(@RequestBody UserCouponsParam param)
        throws BusinessException{
        couponService.UserCouponsSave(param);
        return Result.success();
    }


    @Operation(summary = "用户领取优惠券列表")
    @PostMapping("/marketing/user/receive/list")
    public Result<PageResult<UserCouponsVO>> receiveList(@RequestBody UserCouponQuery couponQuery)throws BusinessException{
        PageResult<UserCouponsVO> voPage =couponService.pageUserCouponsList();
        return new Result<>(voPage);
    }


    @Operation(summary = "查看优惠券码的二维码图片")
    @PostMapping("/marketing/user/receive/detail")
    public Result<UserCouponsVO> receiveDetail(@RequestBody UserCouponCodeQuery query)
        throws BusinessException{
        UserCouponsVO vo= couponService.receiveDetail(query);
        return new Result<>(vo);
//        String dirPath = imagePath;
//        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
//        String datePath = sdf.format(new Date());
//        datePath = datePath.substring(1);
//        File dirFile = new File(dirPath + datePath);
//        QRCodeUtil.createCodeToFile("gfgfddsgdgfsdgds",dirFile,"gfdgdsg");
//        System.out.println(dirFile.getPath());
    }

    @Operation(summary = "修改优惠券状态")
    @PostMapping("/admin/marketing/couponStatus/updateStatus")
    public Result<Void> updateCouponStatus(@RequestBody CouponParam couponParam) throws BusinessException {
        System.out.println(couponParam);
        couponService.updateCouponStatus(couponParam);
        return Result.success();
    }



    @Operation(summary = "编辑优惠券")
    @PostMapping("/admin/marketing/coupon/info/update")
    public Result<Void> updateCoupon(@RequestBody CouponParam couponParam) throws BusinessException {
        System.out.println(couponParam);
        couponService.updateCoupon(couponParam);
        return Result.success();
    }

    @Operation(summary = "删除优惠券")
    @PostMapping("/admin/marketing/coupon/delete")
    public Result<Void> deleteCoupon(@RequestBody CouponParam couponParam) throws BusinessException {
        System.out.println(couponParam);
        couponService.deleteCoupon(couponParam);
        return Result.success();
    }

    @Operation(summary = "导出优惠券列表excel")
    @PostMapping("/admin/marketing/coupon/info/exportCouponExcel")
    public void exportCouponExcel(@RequestBody CouponParam couponParam,HttpServletResponse response) throws BusinessException, UnsupportedEncodingException {
        // 准备导出数据
        String[] headers = {"编号", "优惠券名称", "适用范围", "优惠内容", "状态","数量","有效期","启用状态"};
        List<Map<String, Object>> dataList=new ArrayList<>();
        dataList=couponService.selectAllCoupons();

        String fileName = "优惠券列表.xlsx";
        // 使用 UTF-8 编码中文文件名
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 同时设置 filename 和 filename* 以兼容不同浏览器
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
        try (OutputStream outputStream = new FileOutputStream("优惠券列表.xlsx")) {
            ExcelExporter.exportExcel(headers, dataList, "优惠券", response.getOutputStream());
            System.out.println("Excel文件导出成功！");
        } catch (IOException e) {
            System.out.println("Excel文件导出失败：" + e.getMessage());
            e.printStackTrace();
        }
    }



}
